package edu.scau.cxq.gp.common.config;

import edu.scau.cxq.gp.common.entity.CronEntity;
import edu.scau.cxq.gp.common.utils.FileUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Configuration
@ConfigurationProperties(value = "file-utils")
public class CronConfig {

    @Autowired
    private FileUtils fileUtils;

    private String shellCronFile;

    @Bean
    public CronEntity cronEntity() throws IOException {
        String templateContent = fileUtils.getTemplateContent(shellCronFile);
        CronEntity cronEntity = getEntity(templateContent);

        return cronEntity;
    }

    private CronEntity getEntity(String content) {

        CronEntity cronEntity = new CronEntity();
        Map<String, List<String>> cronMap = new HashMap<>();

        String[] split = content.split("\n");

        for (String s : split) {
            String[] ss = s.split("  ");
            List<String> cronList = cronMap.getOrDefault(ss[1], new ArrayList<>());
            cronList.add(ss[0]);
            cronMap.put(ss[1], cronList);
        }

        cronEntity.setCronMap(cronMap);

        return cronEntity;
    }


}
